from django.shortcuts import render
from rest_framework.response import Response
from .models import *
from rest_framework.views import APIView
import  re,redis,random,jwt


#加密
from  django.contrib.auth.hashers import make_password,check_password
# Create your views here.



#短信验证码
class SMScodeView(APIView):
    def get(self,request):
        mobile=request.query_params.get('mobile')
        if not re.findall('^1[3-9]\d{9}$',mobile):
            return Response({'code':205,'msg':'手机号不正确'})
        set=random.randint(100000,9999999)
        r=redis.Redis(host='localhost',password='123',port=6379,db=4)
        r.set(mobile,set,ex=120)
        r.close()
        return Response({'code':201,'msg':'验证码:%s'%set})



#登录
class LoginView(APIView):
    def post(self,request):
        user_name=request.data.get('username')
        pwd = request.data.get('password')
        phone= request.data.get('phone')
        sms_code= request.data.get('sms_code')
        if not all([user_name,pwd,phone,sms_code]):
            return Response({'code':400,'msg':'数据不完整'})

        r = redis.Redis(host='localhost', password='123', port=6379, db=4)
        set=r.get(phone)
        if set.data.decode() !=sms_code:
            return Response({"code": 400, 'msg': '验证码错误'})
        try:
            user=UserModel.objects.get(username=user_name)
            if  not check_password(pwd,user.password):
                return Response({"code":401,'msg':'密码错误'})
            return  Response({'code':200,'msg':'ok'})
        except:
            UserModel.objects.create(
                username=user_name,
                password=make_password(pwd),
                phone=phone,
            )
        return Response({'code':201,'msg':'登录成功'})
